package com.delivery.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.delivery.adapter.CateChildListViewAdapter;
import com.delivery.common.MyProgressHandler;
import com.delivery.module.CategoriesContent;
import com.delivery.module.ConfigModule;
import com.delivery.service.ICategoriesContent;
import com.delivery.service.impl.CategoriesContentService;
import com.delivery.utils.StringUtils;
import android.app.ListActivity;
import android.view.Gravity;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import android.widget.BaseAdapter;

import android.widget.Toast;

public  final class CateChildActivity extends ListActivity implements OnScrollListener {
	
	protected static final int REST_TIME = 500;
	
	private static final String TAG = "MainActivity";

	//private listViewAdapter1 adapter = new listViewAdapter1();
	private CateChildListViewAdapter adapter = new CateChildListViewAdapter(CateChildActivity.this);
	
	private static List<CategoriesContent> lists = new ArrayList<CategoriesContent>();
	
	public static final int APP_PAGE_SIZE = 3;
	
	private static String categoriesId = "1";
	
	private static String typeId = "1";
	
	private static int currentIndex = 0;
	
	
	private static int totalCount;
	
	private static StringBuffer params = new StringBuffer();
	
	public static MyHandler myHandler;
	
	private Context mContext;
	
	private ListView listView;
	
	private int lastItem = 0;

	LinearLayout loadingLayout;
	
	
	private MyProgressHandler myProgress;
	
	/**
	 * 
	 * 设置布局显示属性
	 */

	private LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);

	/**
	 * 
	 * 设置布局显示目标最大化属性
	 */

	private LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.FILL_PARENT,
			LinearLayout.LayoutParams.FILL_PARENT);

	private ProgressBar progressBar;
	
	private ICategoriesContent categoriesContentService = new CategoriesContentService();
	
	private CategoriesContent categoriesContent = null;
	
	private ImageButton back = null;
	
	private static String type = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.child_item);
		Intent intent = getIntent();
		categoriesContent = (CategoriesContent) intent.getSerializableExtra("categoriesContent");
		mContext = this;
		typeId = getResources().getString(R.categories.type_twtj);
		categoriesId= "";
		currentIndex = 0;
		type = "tab";
		back = (ImageButton) findViewById(R.id.back);
		back.setOnClickListener(new BackListener());
		// 线性布局
		LinearLayout layout = new LinearLayout(this);

		// 设置布局 水平方向

		layout.setOrientation(LinearLayout.HORIZONTAL);

		// 进度条

		progressBar = new ProgressBar(this);

		// 进度条显示位置

		progressBar.setPadding(0, 0, 15, 0);

		// 把进度条加入到layout中

		layout.addView(progressBar, mLayoutParams);

		// 文本内容

		TextView textView = new TextView(this);

		textView.setText("加载中...");

		textView.setGravity(Gravity.CENTER_VERTICAL);
		// 把文本加入到layout中

		layout.addView(textView, FFlayoutParams);

		// 设置layout的重力方向，即对齐方式是

		layout.setGravity(Gravity.LEFT);

		// 设置ListView的页脚layout

		loadingLayout = new LinearLayout(this);

		loadingLayout.addView(layout, mLayoutParams);

		loadingLayout.setGravity(Gravity.LEFT);

		// 得到一个ListView用来显示条目

		listView = getListView();
		listView.setCacheColorHint(Color.TRANSPARENT);
		// 添加到页脚显示

		listView.addFooterView(loadingLayout);
		listView.setDividerHeight(0);

		// 给ListView添加适配器

		setListAdapter(adapter);

		// 给ListView注册滚动监听

		listView.setOnScrollListener(this);
		
		myProgress = new MyProgressHandler(this,1);
		MyProgressThread my = new MyProgressThread();
		new Thread(my).start();
		
		myHandler = new MyHandler(this,1);
	
	}
	
	class BackListener implements OnClickListener{
		public void onClick(View v) {
			backWindow();
		}
	}
	
	private void backWindow(){
		
		Intent intent = new Intent();
		intent.setClass(CateChildActivity.this, MainTabActivity.class);
		startActivity(intent);
		//CateChildActivity.this.finish();
		this.finish();
	}
	
	class MyProgressThread implements Runnable{

		public void run() {
			try {
				Thread.sleep(REST_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			sendProgressMsg("0");
			//起一个线程更新数据
			MyThread m = new MyThread();
			new Thread(m).start();
		}
		
	}
	
	public void sendProgressMsg(String rmsg){
		if(myProgress!=null){
			Message msg = new Message();
			Bundle b = new Bundle();// 存放数据
			b.putString("rmsg", rmsg);
			msg.setData(b);
			myProgress.sendMessage(msg); // 向Handler发送消息,更新UI
		}
	}
	
	class TagQuery implements OnClickListener{
		
		private int categoriesId;
		
		public TagQuery(int categoriesId){
			this.categoriesId = categoriesId;
		}

		public void onClick(View v) {
			sendProgressMsg("2");
			Message msg = new Message();
			Bundle b = new Bundle();// 存放数据
			b.putString("rmsg", "1");
			b.putString("tab", "tab");
			b.putString("categoriesId", String.valueOf(categoriesId));
			msg.setData(b);
			CateChildActivity.myHandler.sendMessage(msg);
		}
	}

	
	// 更新后台数据
	class MyThread implements Runnable {
		public void run() {
			try {
				Thread.sleep(REST_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String msglist = "1";
			Message msg = new Message();
			Bundle b = new Bundle();// 存放数据
			b.putString("rmsg", msglist);
			b.putString("categoriesId", categoriesId);
			b.putString("tab", "");
			msg.setData(b);
			myHandler.sendMessage(msg); // 向Handler发送消息,更新UI

		}
	}
	
	public class MyHandler extends Handler{
		private CateChildActivity mContext;
		public MyHandler(Context conn,int a) {
			mContext = (CateChildActivity)conn;
		}

		public MyHandler(Looper L) {
			super(L);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle b = msg.getData();
			String rmsg = b.getString("rmsg");
			if ("1".equals(rmsg)) {
				if(StringUtils.isNotEmpty(type) && type.equals("tab") && listView!=null){
					currentIndex = 0;
					lists.clear();
					adapter.clearList();
					listView.removeAllViewsInLayout();
					adapter.notifyDataSetChanged();
					type = "";
				}
				if(isNeedQueryData()){
					categoriesId = b.getString("categoriesId");
					getCategoriesContents();
					if(lists == null || lists.size() <=0){
						sendProgressMsg("1");
						return;
					}
					
					int endPage =  (currentIndex <=0 ? 1 : currentIndex+1) * APP_PAGE_SIZE;
					int beginPage = endPage - APP_PAGE_SIZE;
					if(endPage > totalCount){
						endPage = totalCount;
					}
					
					for (int i = beginPage; i < endPage; i++) {
						CategoriesContent cate = lists.get(i);
						adapter.addItem(cate);
					}
				}
				sendProgressMsg("1");
			}
		}
	}
			
	private boolean isNeedQueryData(){
		if(lists!=null && (lists.size() <=0 || lists.size() < totalCount)) 
		return true;
		return false;
	}
	
	public void getCategoriesContents(){
		String json = getCategoriesContentJson();
		if(StringUtils.isEmpty(json)){
			return;
		}
		
		JSONObject jsonObject;
		try {
			jsonObject = new  JSONObject(json);
			String 	total = jsonObject.getString("total");
			CategoriesContent categoriesContent = null;
			totalCount = Integer.parseInt(total);
			JSONArray jsonArray = jsonObject.getJSONArray("results");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jb = jsonArray.getJSONObject(i);
				if(jb != null){
					categoriesContent = new CategoriesContent();
					categoriesContent.setContentDesc(jb.getString("contentDesc"));
					categoriesContent.setImgUrl(jb.getString("imgUrl"));
					categoriesContent.setShareAddress(jb.getString("shareAddress"));
					categoriesContent.setUpdateTime(jb.getString("updateTime"));
					lists.add(categoriesContent);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			return;
		}
	}
	
	/**
	 * 获取远程服务器数据，返回格式是json
	 * @return
	 */
	public String getCategoriesContentJson(){
		params.delete(0, params.length());
		params.append(ConfigModule.GET_CATEGORIESCONTENT_URL);
		params.append("&pageSize="+APP_PAGE_SIZE);
		//params.append("&typeId="+typeId);
		//params.append("&categoriesId="+getCategoriesId());
		params.append("&currentPage="+currentIndex);
		params.append("&type=level2");
		if(categoriesContent!=null){
			params.append("&childId="+categoriesContent.getId());
		}
		System.out.println(params);
	     try {
	    	 return  this.categoriesContentService.getCategoriesContents(String.valueOf(params));
		 } catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "query categoriesContentService is fail.");
			return "";
		 }
	}
	
	private String getCategoriesId(){
		if(StringUtils.isEmpty(categoriesId) || categoriesId.equals("0")){
			return "";
		}
		return getResources().getString(Integer.parseInt(categoriesId));
	}
	
	private SimpleAdapter buildSimpleAdapter(List<CategoriesContent> categoriesContents){
		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
		HashMap<String, String> map =null;
		for (Iterator iterator = categoriesContents.iterator(); iterator.hasNext();) {
			CategoriesContent categoriesContent = (CategoriesContent) iterator.next();
			map = new HashMap<String, String>();
			map.put("contentDesc",categoriesContent.getContentDesc());
			list.add(map);
		}
		return new SimpleAdapter(this,list,R.layout.child_info,new String[]{"contentDesc"},new int[]{R.id.content_desc});
	}
	
	public void onScroll(AbsListView v, int firstVisibleItem,int visibleItemCount, int totalItemCount) {

		lastItem = firstVisibleItem + visibleItemCount - 1;

		if (adapter.count <= totalCount) {

			if (firstVisibleItem + visibleItemCount == totalItemCount) {
				adapter.count += APP_PAGE_SIZE;
				
				listView.setSelection(lastItem);
				
				int currentPage = adapter.count / APP_PAGE_SIZE;
				
				Toast.makeText(getApplicationContext(),
						"第" + currentPage + "页", Toast.LENGTH_LONG).show();
				scrollQueryData();
			}
		}
		else {

			listView.removeFooterView(loadingLayout);

		}

	}
	
	public void scrollQueryData(){
		sendProgressMsg("2");
		Message msg = new Message();
		currentIndex++;
		//System.out.println("currentIndex:"+currentIndex);
		Bundle b = new Bundle();// 存放数据
		b.putString("rmsg", "1");
		b.putString("tab", "");
		b.putString("categoriesId", String.valueOf(categoriesId));
		msg.setData(b);
		CateChildActivity.myHandler.sendMessage(msg);
	}

	public void onScrollStateChanged(AbsListView v, int state) {

		/*if (lastItem == adapter.count
				&& state == OnScrollListener.SCROLL_STATE_IDLE) {

			Log.i(TAG, "ScrollStateChanged>>>state:" + state + "lastItem:"
					+ lastItem);

			// 显示50条ListItem，即0-49，因为onScrollStateChanged是在“拖动滑动”执行过之后才触发，所以用adapter.count<=41作条件

			if (adapter.count <= totalCount) {
				adapter.count += APP_PAGE_SIZE;
			}

		}*/

	}

	/**
	 * 
	 * 要用用于生成显示数据
	 * 
	 * @author huangbq
	 * 
	 * 
	 */

	class listViewAdapter1 extends BaseAdapter {

		int count = 10;

		public int getCount() {


			return count;

		}

		public Object getItem(int pos) {

			Log.i(TAG, "getItem>>>pos:" + pos);

			return pos;

		}

		public long getItemId(int pos) {

			Log.i(TAG, "getItemId>>>ItemId:" + pos);

			return pos;

		}

		public View getView(int pos, View v, ViewGroup p) {

			TextView view;

			if (v == null) {

				view = new TextView(CateChildActivity.this);

			}

			else {

				view = (TextView) v;

			}

			view.setText("ListItem " + pos);

			view.setTextSize(20f);

			view.setGravity(Gravity.CENTER);

			view.setHeight(60);

			return view;

		}

	}

}
